import {React, useState, useEffect} from "react";
import {Button, DatePicker,ImageUploader, Form, Input, Picker, Toast} from "antd-mobile";
import {useTranslation} from "react-i18next";
import {LeftOutline} from "antd-mobile-icons";
import {useNavigate} from "react-router-dom";
import {bind_bank, uploadImg} from "@/request/api";

export default function addCard(){
    const { t, i18n } = useTranslation();
    const [type, setType] = useState(2)
    const navigate = useNavigate();

    const [fileList, setFileList] = useState([])
    const [reverse_card, setReverse_card] = useState([])

    function limitToTwoDecimalPlaces(value) {
        // 移除非数字和小数点的字符
        value += ''
        value = value.replace(/[^\d.]/g, '');

        // 限制只有一个小数点
        value = value.replace(/^(\d+)\./g, '$1.');
        value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');

        // 限制小数点后只能有两个数字
        value = value.replace(/(\d)\.(\d{3})/, '$1.$2');

        // 如果值为0开头，则允许输入小数点
        value = value.replace(/^0+(?=\d)/g, '');


        // 如果小数点后有超过两位数字，则去掉多余的数字
        var temp = value.split('.');
        if (temp.length > 1 && temp[1].length > 2) {
            value = temp[0] + '.' + temp[1].substr(0, 2);
        }
        return value
    }
    const onFinish = (v)=>{
        console.log(v)
        // /my/bind_bank
        // bank_type 1银行卡 2usdt
        // bankname 所属银行或 usdt类型
        // cardnum 银行卡号或者钱包地址
        // username 真实姓名
        v.bank_type = v.bank_type[0]
        if(v.bank_type == 2){
            v.bankname = v.bankname_type[0]
            delete v.bankname_type
        }else {
            v.frond_card = v.frond_card[0].url
            v.reverse_card = v.reverse_card[0].url
        }
        Toast.show({
            icon: 'loading',
        })
        console.log(fileList, v)
        // return false;
        bind_bank(v).then(res => {
            if (res.code == 0){
                Toast.show({
                    icon: 'success',
                    content: res.info,
                })
                navigate(-1)
            }
            Toast.clear()
        })
    }

    const selectType = (v) =>{
        setType(v[0])
    }

    const picUpload = async (file) =>{
        const formData = new FormData();
        formData.append('pic', file);
        let res =  await uploadImg(formData)
        return {url : res.data}
    }
    return (
        <>
            <div className='header'>
                <div className='backIcon' onClick={() => { navigate(-1) }}>
                    <LeftOutline />
                </div>
                <p>{t('pcs2')}</p>
            </div>
            <div className="recharge">
                <Form layout='horizontal' onFinish={onFinish} initialValues={{bank_type: [2], bankname_type: ['usdt_trc']}}>
                    <Form.Item label={t('pcs8')} name="bank_type"
                               rules={[{ required: true, message: t("pcs1")}]} trigger='onConfirm' onClick={(e, pickerRef) => {
                       pickerRef.current?.open();console.log(pickerRef)
                    }}>
                        <Picker
                            cancelText={t('ty2')}
                            confirmText={t('ty1')}
                            columns={[
                                [
                                    { label: 'USDT', value: 2 },
                                    { label: 'BANK', value: 1 },
                                ]
                            ]}
                            // defaultValue={[type]}
                            onConfirm={selectType}
                        >
                            {(items) => {
                                return (
                                    items.every(item => item === null)
                                        ? <span style={{color: '#ccc'}}>{t('pcs1')}</span>
                                        : items.map(item => item?.label ?? t('pcs1')).join('')
                                )
                            }}
                        </Picker>
                    </Form.Item>
                    {
                        type == 2 && (
                            <Form.Item required label={t('pcs9')} rules={[{ required: true, message: t("pcs1")}]} name="bankname_type" trigger='onConfirm' onClick={(e, pickerRef) => {
                                pickerRef.current?.open();console.log(pickerRef)
                            }}>
                                <Picker
                                    cancelText={t('ty2')}
                                    confirmText={t('ty1')}
                                    columns={[
                                        [
                                            { label: 'usdt_trc', value: 'usdt_trc' },
                                            { label: 'usdt_erc', value: 'usdt_erc' },
                                        ]
                                    ]}
                                    // defaultValue={[type]}
                                >
                                    {(items) => {
                                        return (
                                            items.every(item => item === null)
                                                ? <span style={{color: '#ccc'}}>{t('pcs1')}</span>
                                                : items.map(item => item?.label ?? t('pcs1')).join('')
                                        )
                                    }}
                                </Picker>
                            </Form.Item>
                        )
                    }
                    {
                        type == 2 && (
                            <Form.Item required rules={[{ required: true, message: t("pcs3") }]} label={t('pcs7')} name="cardnum" >
                                <Input  placeholder={t("pcs3")} clearable />
                            </Form.Item>
                        )
                    }
                    {
                        type == 1 && (
                            <Form.Item required rules={[{ required: true, message: t("pcs3") }]} label={t('pcs6')}  name="bankname">
                                <Input placeholder={t("pcs3")} onChange={(val)=>{
                                }} clearable />
                            </Form.Item>
                        )
                    }
                    {
                        type == 1 && (
                            <Form.Item required rules={[{ required: true, message: t("pcs3") }]} label={t('pcs5')} name="username">
                                <Input  placeholder={t("pcs3")} onChange={(val) => {
                                }} clearable/>
                             </Form.Item>
                        )
                    }
                    {
                        type == 1&& (
                            <Form.Item required rules={[{ required: true, message: t("pcs3") }]} label={t('pcs4')} name="cardnum">
                                <Input  placeholder={t("pcs3")} onChange={(val)=>{
                                }} clearable />
                            </Form.Item>
                        )
                    }
                    {
                        type == 1&& (
                            <Form.Item required rules={[{ required: true, message: t("pcs3") }]} label={t('pcs13')} name="frond_card">
                                <ImageUploader
                                    style={{ '--cell-size': '90px' }}
                                    columns={1}
                                    maxCount={1}
                                    upload={picUpload}
                                    value={fileList}
                                    onChange={setFileList}
                                />
                            </Form.Item>
                        )
                    }

                    {
                        type == 1&& (
                            <Form.Item required rules={[{ required: true, message: t("pcs3") }]} label={t('pcs14')} name="reverse_card">
                                <ImageUploader
                                    style={{ '--cell-size': '90px' }}
                                    columns={1}
                                    maxCount={1}
                                    upload={picUpload}
                                    value={reverse_card}
                                    onChange={setReverse_card}
                                />
                            </Form.Item>
                        )
                    }

                    <Form.Item>
                        <Button className="pay-money" type='submit' block color='primary' >
                            {t('ty3')}
                        </Button>
                    </Form.Item>
                </Form>

            </div>
        </>
    )
}
